package demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * date:2025.11.18
 * title:线程通信demo
 */
public class Udp {


    public static void main(String[] arg) {
        Server server = new Server("服务端");
        Client client = new Client("客户端");
        server.start();
        client.start();

    }
}

class Client extends Thread {
    Client(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("服务端开机");
        Scanner sc = new Scanner(System.in);
            try {
                DatagramSocket datagramSocket = new DatagramSocket();
                InetAddress inetAddress = InetAddress.getByName("7.247.153.221");
                System.out.println("开始输入字符，输入exit退出程序");
                StringBuilder sb;
                while (true) {
                    String s = sc.nextLine();
                    if (s.equals("exit")){
                        System.out.println("退出传递");
                        datagramSocket.close();
                        return;
                    }
                    byte[] bys = s.getBytes();
                    //开始打包数据
                    DatagramPacket dp = new DatagramPacket(bys, bys.length, inetAddress, 10086);
                    datagramSocket.send(dp);
                    datagramSocket.close();
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                sc.close();
            }
    }
}

class Server extends Thread {

    Server(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("客户端开机");
        while (true) {
            try {
                DatagramSocket ds  = new DatagramSocket(10086);
                byte[] bys = new byte[1024];
                DatagramPacket dp =new DatagramPacket(bys,bys.length);
                ds.receive(dp);
                int length = dp.getLength();
                byte[] getData = dp.getData();
                System.out.println("客户端收到: "+new String(getData,0,length));
                ds.close();
            } catch (SocketException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }
}
